#include <vector>
#include <iostream>
using namespace std;
  struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode() : val(0), left(nullptr), right(nullptr) {}
      TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
      TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  };
 
class Solution {
	
public:
	TreeNode* build(vector<int>& inorder,vector<int>& postorder,int& nIdx,int nMidBegin,int nMidEnd){
		
		if(nMidBegin>nMidEnd || nIdx<0){
			return nullptr;
		}
		TreeNode* root=new TreeNode(postorder[nIdx]);
		int nSpit=nMidBegin;
		while(inorder[nSpit]!=root->val){
			++nSpit;
		}
		--nIdx;
		TreeNode* right=build(inorder,postorder,nIdx,nSpit+1,nMidEnd);
		TreeNode* left=build(inorder,postorder,nIdx,nMidBegin,nSpit-1);
		root->left=left;
		root->right=right;
		return root;
	}
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        
        int nIdx=postorder.size()-1;
        return build(inorder,postorder,nIdx,0,inorder.size()-1);
    }
};
